package com.example.blogother.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class ImageShuiUtil {


    public static void addTextWatermark(String text, File sourceImageFile, File destImageFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(sourceImageFile);
            Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();

            // 初始化水印文本的字体、颜色和透明度
            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.15f);
            g2d.setComposite(alphaChannel);
            g2d.setColor(Color.GRAY);
            g2d.setFont(new Font("微软雅黑", Font.BOLD, 64));
            FontMetrics fontMetrics = g2d.getFontMetrics();
            int textWidth = fontMetrics.stringWidth(text);
            int textHeight = fontMetrics.getHeight();

            // 循环绘制水印文本，覆盖整个图像
            for (int x = 0; x < sourceImage.getWidth(); x += textWidth + 20) {
                for (int y = textHeight; y < sourceImage.getHeight(); y += textHeight + 20) {
                    g2d.drawString(text, x, y);
                }
            }

            ImageIO.write(sourceImage, "png", destImageFile);
            g2d.dispose();

            System.out.println("Text watermark added successfully.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        File sourceImageFile = new File("D:\\java\\blog\\blog-index\\src\\main\\resources\\static\\image\\1a405487-3043-4df3-846d-a4a886560c0e.jpg");
        File destImageFile = new File("D:/java/blog/blog-other/src/main/resources/static/image/6.jpg");
        String watermarkText = "李四";

        addTextWatermark(watermarkText, sourceImageFile, destImageFile);
    }
}